import React, { useState, useRef, useEffect } from 'react'
import './style.less'
import { message, useNewPage } from '@hs-admin/utils'
import { deleteWebsiteProduct, deleteDataCollect, moveUpDataProductList, moveDownDataProductList } from '@/api/assetMaintain/dataProduct'
import { useSearchParams } from 'react-router-dom'
import { Button, Flex, Popconfirm, Space, Form } from 'antd'
import { HsAdminForm, HsAdminTablePage } from '@hs-admin/base-components'
import WebsiteModal from './Website'
import ServiceModal from './ItemSet'
import MoveSort from '@/components/global/NewMoveSort'
import { handleButtonShow } from '@/utils/tools'
import { getProductItemSetList } from '@/api/assetMaintain/dataProduct/item_set'
import { getProductWebsiteList } from '@/api/assetMaintain/dataProduct/website'
import { HsAdminSelectProductCategory } from '@/components/global'

interface Props {
  source: 'item_set' | 'website'
}
const OperationChild: React.FC<Props> = (props: Props) => {
  const { source } = props
  const [searchParams] = useSearchParams()
  const [data, setdata] = useState<any[]>([])
  const [form] = Form.useForm()
  const formItemOptions = [
    {
      label: '产品名称',
      name: 'keywords',
      component: 'Input',
      FormItemColProps: {
        span: 12
      },
      componentProps: {
        onPressEnter: searchList
      }
    },
    {
      label: '类别',
      name: 'tags_id',
      slot: 'tags_id',
      FormItemColProps: {
        span: 12
      }
    }
  ]
  const [selectCategoryInfor, setselectCategoryInfor] = useState<any>({
    hasInit: false
  })
  const [selectCategoryOptions, setselectCategoryOptions] = useState<any[]>([])
  const { pagination, resetPage }: { pagination: UsePageProps; resetPage: () => void } = useNewPage(callList, selectCategoryInfor)

  const WebsiteModalRef = useRef<any>(null)
  const serviceModalRef = useRef<any>(null)

  function dropSelect() {
    if (source === 'website') {
      WebsiteModalRef.current.showModal()
    } else {
      serviceModalRef.current.showModal()
    }
  }
  function moveUp(record: any) {
    moveUpDataProductList({ id: record.id, tags: [searchParams?.get('name')] }).then(() => {
      message.success('上移成功')
      callList()
    })
  }
  function moveDown(record: any) {
    moveDownDataProductList({ id: record.id, tags: [searchParams?.get('name')] })
      .then(() => {
        message.success('下移成功')
        callList()
      })
      .finally(() => {})
  }
  function reset() {
    form.resetFields()
    setselectCategoryInfor({ hasInit: true })
    setselectCategoryOptions([])
    resetPage()
  }
  function searchList() {
    resetPage()
  }
  function callList() {
    const fieldsValues = form.getFieldsValue()
    let callFn = getProductItemSetList
    if (source === 'website') {
      callFn = getProductWebsiteList
    }
    return callFn({
      keywords: fieldsValues.keywords,
      tags: selectCategoryInfor?.label,
      page: pagination.current,
      page_size: pagination.pageSize
    }).then((res) => {
      setdata(res.items ?? [])
      return res
    })
  }
  const columns = [
    {
      title: '移动',
      dataIndex: 'move',
      width: 120,
      render: (_text: string, record: any, index: number) => (
        <MoveSort pagination={pagination} record={record} index={index} data={data} moveUp={moveUp} moveDown={moveDown} />
      )
    },
    {
      title: '产品名称',
      dataIndex: 'name'
    },
    {
      title: '产品描述',
      dataIndex: 'description',
      ellipsis: true
    },
    {
      title: '类别',
      dataIndex: source === 'item_set' ? 'item_set_tag.name' : 'website_tag.name'
    },
    {
      title: '最新编辑用户',
      dataIndex: 'owner.name'
    },
    {
      title: '最新维护时间',
      dataIndex: 'updated_at',
      type: 'datetime'
    },
    {
      title: '操作',
      key: 'actions',
      render: (_text: string, record: any) => (
        <Flex gap="small">
          {handleButtonShow('datashop.product.update') && (
            <Button
              type="link"
              onClick={() => {
                if (source === 'website') {
                  WebsiteModalRef.current.showModal(record)
                } else {
                  serviceModalRef.current.showModal(record)
                }
              }}>
              编辑
            </Button>
          )}
          {handleButtonShow('datashop.product.delete') && (
            <Popconfirm
              title="警告"
              description="确定删除该项吗?"
              onConfirm={async () => {
                let callFn = deleteWebsiteProduct
                if (source === 'item_set') {
                  callFn = deleteDataCollect
                }
                callFn({ id: record.id })
                  .then(() => {
                    message.success('删除成功')
                    searchList()
                  })
                  .finally(() => {})
              }}>
              <Button type="link">删除</Button>
            </Popconfirm>
          )}
        </Flex>
      )
    }
  ]

  useEffect(() => {
    if (searchParams.get('id')) {
      form.setFieldValue('tags_id', searchParams.get('id'))
      setselectCategoryInfor({ id: searchParams.get('id'), label: searchParams.get('label'), hasInit: true })
      setselectCategoryOptions([{ label: searchParams.get('label'), value: searchParams.get('id') }])
      resetPage()
    } else {
      setselectCategoryInfor({ hasInit: true })
    }
  }, [])

  return (
    <div className="pr-4 pl-4 mt-4">
      <h2 className="font-bold">金融数据产品内容</h2>
      <Flex justify="space-between">
        <HsAdminForm form={form} formItemOptions={formItemOptions} label-placement="left" className="w-1/2">
          <div slot="tags_id">
            <Form.Item name="tags_id">
              <HsAdminSelectProductCategory
                source={source}
                options={selectCategoryOptions}
                onChange={(_: any, option: any) => {
                  setselectCategoryInfor({ ...option, hasInit: true })
                  searchList()
                }}
                placeholder="请选择类别"
              />
            </Form.Item>
          </div>
        </HsAdminForm>
        <Space>
          <Button onClick={reset}>重置</Button>
          <Button type="primary" onClick={searchList}>
            查询
          </Button>
        </Space>
      </Flex>
      <Flex justify="space-between" align="center">
        <h3>产品内容列表</h3>
        {handleButtonShow('datashop.product.create') && (
          <Button type="primary" onClick={() => dropSelect()}>
            新增产品
          </Button>
        )}
      </Flex>
      <br />
      <HsAdminTablePage columns={columns} dataSource={data} pagination={pagination} rowKey="id" id="J-item-set-website-child" />
      <WebsiteModal ref={WebsiteModalRef} category_id={searchParams.get('id')} finish={searchList} source={source} />
      <ServiceModal ref={serviceModalRef} category_id={searchParams.get('id')} finish={searchList} source={source} />
    </div>
  )
}

export default OperationChild
